<template>
	<div class="customer-el-form">
		<el-form
			ref="formRef"
			:model="formData"
			:rules="formDataRules"
			:validate-on-rule-change="false"
			@validate="triggerValidate">
			<el-form-item
				label="组名"
				prop="group">
				<el-input v-model="formData.group" />
			</el-form-item>
			<div
				v-for="(person, personIndex) in formData.list"
				:key="personIndex">
				<el-form-item
					label="用户名"
					:prop="`list.${personIndex}.name`"
					:rules="formDataRules.name">
					<el-input v-model="person.name" />
				</el-form-item>
				<div v-if="personIndex !== formData.list.length - 1">-------------------------------</div>
			</div>
		</el-form>
		<button @click="addPerson">增加</button>
	</div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { useValidForm } from './hooks/useValidForm';

const { formRef, triggerValidate, i18n } = useValidForm();
const formData = ref({
	group: '',
	list: [
		{
			name: '',
			age: null,
		},
	],
});

const formDataRules = computed(() => {
	return {
		group: {
			required: true,
			trigger: ['blur', 'change'],
			message: i18n.t('user.groupEmpty'),
		},
		name: {
			required: true,
			trigger: ['blur', 'change'],
			message: i18n.t('user.nameEmpty'),
		},
		age: {
			required: true,
			trigger: ['blur', 'change'],
			message: i18n.t('user.ageEmpty'),
		},
	};
});

// 动态添加数据
const addPerson = () => {
	formData.value.list.push({
		name: '',
		age: null,
	});
};
</script>

<style lang="less" scoped>
.customer-el-form {
	width: 20rem;
}
</style>
